package com.gxa.order.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.order.dao.ArtOrderDao;
import com.gxa.order.dao.MacOrderDao;
import com.gxa.order.dao.OrderCancelDao;
import com.gxa.order.dao.OrderFightDao;
import com.gxa.order.dto.MailDTO;
import com.gxa.order.dto.PageParam;
import com.gxa.order.param.PastLikeParam;
import com.gxa.order.param.PastParam;
import com.gxa.order.param.PastTicketParam;
import com.gxa.order.param.TicketParam;
import com.gxa.order.service.CheckService;
import com.gxa.order.service.PastTicketService;
import com.gxa.order.service.TicketService;
import com.gxa.order.service.UserService;
import dto.ResultDTO;
import entity.*;
import exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.Response;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author htt
 * @create 2021-05-11
 * project overview
 */
@Service("pastTicketService")
@Slf4j
public class PastTicketServiceImpl implements PastTicketService {

    @Resource
    private ArtOrderDao artOrderDao;

    @Resource
    private MacOrderDao macOrderDao;

    @Autowired
    private TicketService ticketService;

    @Resource
    private OrderCancelDao orderCancelDao;

    @Autowired
    private UserService userService;
    
    @Autowired
    private CheckService checkService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private  OrderCancelDao orderCancel;

    @Resource
    private OrderFightDao orderFightDao;


    /**
     * 查询历史订单
     * @param memberId
     * @return
     */
    @Override
    public ResultDTO findPastTicket(Integer memberId, PastLikeParam likeParam) {
        // 查询到的列表
        List<TicketParam> listArt = new ArrayList<>();
        List<TicketParam> listMac = new ArrayList<>();
        if (memberId == null) {
            return Response.error(1001, "用户的id不能为空！");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //调用user的接口验证该用户是否存在
        //***
        ResultDTO member = userService.findAllById(memberId);
        if (member.getData() == null){
            throw new SystemException(1001, "该用户不存在！");
        }

        Member members = objectMapper.convertValue(member.getData(), Member.class);
        //查询人工订单
        //Integer num = pageParam.getPageSize() > 2 ? 2 : pageParam.getPageSize();
        //System.out.println("********************"+num+"***********"+pageParam.getPageNum());
        //Integer num1 = pageParam.getPageSize()-num > 0 ? pageParam.getPageSize()-num : 0;

        PageHelper.startPage(likeParam.getPageNum(), likeParam.getPageSize());
        List<ArtOrder> artList = artOrderDao.findAllArtOrder(memberId, likeParam);
        for (ArtOrder artOrder : artList) {
            TicketParam param = new TicketParam();
            param.setStartTime("请点击详情查看");
            param.setEndPlace("请点击详情查看");
            param.setFlightMsg("请点击详情查看");
            param.setMemberName(members.getMemberName());
            param.setOrderId(artOrder.getArtOrderId());
            param.setStatus(artOrder.getArtOrderStatus());
            param.setApplyMember(members);
            param.setType(0);
            // 如果是取消订单，查询取消原因
            if (artOrder.getArtOrderStatus() == 3) {
                param.setCancelMsg(orderCancel.find(artOrder.getArtOrderId(), 0));
            }
            // 拒绝理由
            if (artOrder.getArtOrderStatus() == 2) {
                ResultDTO resultDTO = checkService.checkOrder(artOrder.getArtOrderId(), 0);
                if (resultDTO.getData() != null) {
                    ExaminePeople examinePeople = objectMapper.convertValue(resultDTO.getData(), ExaminePeople.class);
                    param.setRefuseMsg(examinePeople.getExaRefuseDesc());
                }
            }
            // 调用user的接口查询员工信息
            // ***
            ResultDTO member1 = userService.findAllById(artOrder.getMemberId());
            if (member1.getData() == null){
                throw new SystemException(1001, "该用户不存在！");
            }
            Member member1s = objectMapper.convertValue(member1.getData(), Member.class);
            param.setMember(member1s);
            param.setArtOrder(artOrder);
            // 调用审核接口查询审核人
            // ***
            ResultDTO resultDTO = checkService.exaArtOrderMember(artOrder.getArtOrderId());
            if (resultDTO.getData() != null){
                String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                param.setCheckPerson(s);
            }

            listArt.add(param);
        }
        // 机器订单
        PageHelper.startPage(likeParam.getPageNum(), likeParam.getPageSize());
        List<MacOrder> macList = macOrderDao.findAllOrder(memberId, likeParam);
        //调用飞机的接口
        //***
//____________________________________________________________________________________
        /*ResultDTO all = ticketService.findByFlightIdList(macList);
        if (all == null) {
            throw new SystemException(1001, "没有机票！");
        }
        //List<MacOrder> macOrders = (List<MacOrder>) all.getData();
        *//*ObjectMapper objectMapper = new ObjectMapper();
        List<MacOrder> list = (List<MacOrder>)objectMapper.convertValue(all.getData(), List.class);
        for (Object macOrder : list) {
           log.info("**************************"+macOrder);
        }*//*
        ObjectMapper objectMapper = new ObjectMapper();
        String tranStr = null;
        List<MacOrder> macOrderList = null;
        try {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, MacOrder.class);
            tranStr = all.getData().toString();
            macOrderList =  (List<MacOrder>)objectMapper.readValue(tranStr, javaType);
            macOrderList = objectMapper.readValue(tranStr, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }*/
        List<MacOrder> macOrders = macList;
        for (MacOrder macOrder : macOrders) {
            TicketParam param = new TicketParam();
            param.setType(1);
            param.setStatus(macOrder.getMacOrderStatus());
            param.setOrderId(macOrder.getMacOrderId());
            param.setMemberName(members.getMemberName());
            param.setApplyMember(members);
            // 取消原因
            if (macOrder.getMacOrderStatus() == 3) {
                param.setCancelMsg(orderCancel.find(macOrder.getMacOrderId(), 1));
            }
            // 拒绝理由
            if (macOrder.getMacOrderStatus() == 2) {
                ResultDTO resultDTO = checkService.checkOrder(macOrder.getMacOrderId(), 1);
                if (resultDTO.getData() != null) {
                    Examine examine = objectMapper.convertValue(resultDTO.getData(), Examine.class);
                    if (examine.getExamineFirstIsPoss() == 0) {
                        param.setRefuseMsg(examine.getExamineFirstRefuseDesc());
                    }else if (examine.getExamineSecondIsPoss() == 0) {
                        param.setRefuseMsg(examine.getExamineSecondRefuseDesc());
                    }
//                    param.setRefuseMsg(examine.getExamineFirstRefuseDesc()+examine.getExamineSecondRefuseDesc());
                }
            }
            // 调用user的接口查询员工信息
            // ***
            ResultDTO member3 = userService.findAllById(macOrder.getMemberId());
            if (member3.getData() == null){
                throw new SystemException(1001, "该用户不存在！");
            }
            Member member3s = objectMapper.convertValue(member3.getData(), Member.class);
            param.setMember(member3s);
            // 调用审核接口查询审核人
            // ***
            //______________________________________________________________
            ResultDTO resultDTO = checkService.exaMacOrderMember(macOrder.getMacOrderId());
            if (resultDTO.getData() != null){
                String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                param.setCheckPerson(s);
            }
            ResultDTO member2 = userService.findAllById(macOrder.getMemberId());
            if (member2.getData() == null){
                throw new SystemException(1001, "该用户不存在！");
            }
            Member member2s = objectMapper.convertValue(member2.getData(), Member.class);
            param.setMember(member2s);
            if (macOrder.getOrderFights() == null || macOrder.getOrderFights().size() == 0) {
                continue;
            }
            for (OrderFight orderFight : macOrder.getOrderFights()) {
                if (orderFight == null){
                    break;
                }
                if (orderFight.getFlight() == null){
                    continue;
                }
                param.setEndPlace(orderFight.getFlight().getFlightEndAirport());
                param.setStartTime(orderFight.getFlight().getFlightStartTime().toString());
                param.setFlightMsg(orderFight.getFlight().getFlightCode());
                param.setMacOrder(macOrder);
            }

            listMac.add(param);
        }
        PageInfo<TicketParam> pageInfoMac = new PageInfo<>(listMac);
        pageInfoMac.setTotal(macOrderDao.macCount(memberId, likeParam));
        PageInfo<TicketParam> pageInfoArt = new PageInfo<>(listArt);
        pageInfoArt.setTotal(artOrderDao.artCount(memberId, likeParam));
        PastTicketParam ticketParam = new PastTicketParam();
        ticketParam.setWaitOutTicket(artOrderDao.findStatusFour(memberId)+macOrderDao.findStatusFour(memberId));
        ticketParam.setOutTicket(artOrderDao.findStatusFive(memberId)+macOrderDao.findStatusFive(memberId));
        ticketParam.setWaitCheckTicket(artOrderDao.findStatusOne(memberId)+macOrderDao.findStatusOne(memberId));
        PastParam pastParam = new PastParam();
        pastParam.setPageInfoArt(pageInfoArt);
        pastParam.setPageInfoMac(pageInfoMac);
        pastParam.setParam(ticketParam);
        return Response.success(200, "成功！", pastParam);
    }

    /**
     * 取消
     * @param orderId
     * @param type
     * @return
     */
    @Override
    public ResultDTO updateStatus(Integer orderId, Integer type, String msg) {
        if (orderId == null || type == null) {
            throw new SystemException(1001, "员工的id和订单类型不能为空！");
        }
        //添加取消原因
        OrderCancel cancel = new OrderCancel();
        cancel.setOrderId(orderId);
        cancel.setCancelMsg(msg);
        cancel.setOrderType(type);
        // 人工订单
        if (type == 0){
            ArtOrder order = artOrderDao.queryById(orderId);
            if (order.getArtOrderStatus() == 1){
                ArtOrder artOrder = new ArtOrder();
                artOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                artOrder.setArtOrderStatus(3);
                artOrder.setArtOrderId(orderId);
                Integer integer = artOrderDao.updateStatus(artOrder);
                int insert = orderCancelDao.insert(cancel);
                if (integer > 0 && insert > 0){
                    return Response.success(200, "取消成功！");
                }
                throw new SystemException(1001, "取消失败！");
            }
            throw new SystemException(1001, "只有待出票订单可以取消!");
        }
        // 机器订单
        if (type == 1){
            MacOrder macOrder = macOrderDao.queryById(orderId);
            if (macOrder.getMacOrderStatus() == 1){
                MacOrder order1 = new MacOrder();
                order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                order1.setMacOrderStatus(3);
                order1.setMacOrderId(orderId);
                Integer integer = macOrderDao.updateStatus(order1);
                int insert = orderCancelDao.insert(cancel);
                if (integer > 0 && insert > 0){
                    return Response.success(200, "取消成功！");
                }
                throw new SystemException(1001, "取消失败！");
            }

            throw new SystemException(1001, "只有待审核订单可以取消!");
        }
        throw new SystemException(1001, "取消失败！");
    }

    @Override
    public ResultDTO sendEmail(Integer orderId, Integer type) {
        if (orderId == null || type == null) {
            throw new SystemException(1001, "员工的id和订单类型不能为空！");
        }
        // 在user查询管理员的邮箱
        // ***
        ResultDTO resultDTO = userService.selectEmail();
        if (resultDTO.getData() == null){
            throw new SystemException(1001, "你的管理员还没有添加自己的邮箱，请耐心等待！");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.convertValue(resultDTO.getData(), String.class);
        // 人工订单
        if (type == 0){
            ArtOrder order = artOrderDao.queryById(orderId);
            if (order == null) {
                throw new SystemException(1001, "没有该订单");
            }
            if (order.getArtOrderStatus() == 4 || order.getArtOrderStatus() == 1 || order.getArtOrderStatus() == 0){
                if (order.getIsUrgency() == 0){
                    // 在email发送邮箱
                    // ***
                    MailDTO mailDTO = new MailDTO();
                    mailDTO.setSubject("用户出票加急");
                    String[] to = {s};
                    String[] cc = {"377576540@qq.com"};
                    mailDTO.setTo(to);
                    mailDTO.setCc(cc);
                    mailDTO.setText("机械订单号为:"+orderId+"的用户急需机票，请你加快审核！");
                    rocketMQTemplate.convertAndSend("order-urgent", mailDTO);
                    // 修改加急状态
                    ArtOrder artOrder = new ArtOrder();
                    artOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    artOrder.setIsUrgency(1);
                    artOrder.setArtOrderId(orderId);
                    if (artOrderDao.updateUrgency(artOrder) > 0) {
                        return Response.success(200, "加急状态修改成功！");
                    }
                    throw new SystemException(1001, "加急状态修改失败！");
                }
                throw new SystemException(1001, "你已经加急过了，请耐心等待！");

            }
            throw new SystemException(1001, "该状态不能加急！");
        }
        // 机器订单
        if (type == 1){
            MacOrder macOrder = macOrderDao.queryById(orderId);
            if (macOrder == null) {
                throw new SystemException(1001, "没有该订单");
            }
            if (macOrder.getMacOrderStatus() == 4 || macOrder.getMacOrderStatus() == 1 || macOrder.getMacOrderStatus() == 0){
                if (macOrder.getIsUrgency() == 0){
                    // 在user查询管理员的邮箱
                    // ***
                    // 在email发送邮箱
                    // ***
                    MailDTO mailDTO = new MailDTO();
                    mailDTO.setSubject("用户出票加急");
                    String[] to = {s};
                    String[] cc = {"377576540@qq.com"};
                    mailDTO.setTo(to);
                    mailDTO.setCc(cc);
                    mailDTO.setText("机械订单号为:"+orderId+"的用户急需机票，请你加快审核！");
                    rocketMQTemplate.convertAndSend("order-urgent", mailDTO);
                    // 修改加急状态
                    MacOrder order1 = new MacOrder();
                    order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    order1.setIsUrgency(1);
                    order1.setMacOrderId(orderId);
                    if (macOrderDao.updateUrgency(order1) > 0) {
                        return Response.success(200, "加急状态修改成功！");
                    }
                    throw new SystemException(1001, "加急状态修改失败！");
                }
                throw new SystemException(1001, "你已经加急过了，请耐心等待！");
            }
            throw new SystemException(1001, "该状态不能加急!");
        }
        throw new SystemException(1001, "加急失败");
    }

    /**
     * 查询地址
     * @return
     */
    @Override
    public ResultDTO findA() {
        List<String> list = orderFightDao.findAirport();
        return Response.success(200, "success", list);
    }


}
